﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using SomeGame.Actors.Types;
using SomeGame.Zones;

namespace SomeGame.Actors.Components {

    public class Animation : ActorComponent {

        public string Name;
        private readonly Body Body; // Bounds changed by this component.
        private readonly Appearance Appearance; // Texture changed by this component.
        private readonly IList<AnimationFrame> Frames;
        private AnimationFrame CurrentFrame;
        private double ElapsedSecondsThisFrame;
        private readonly int FrameCount;
        private bool IsReadyToShowNextFrame;
	    private bool HasFinishedShowingLastFrame;
        private int NextFrameIndex;

        public Animation(string name, Body body, Appearance appearance, IList<AnimationFrame> frames) {
            Name = name;
            Body = body;
            Appearance = appearance;
            Frames = frames;
            FrameCount = frames.Count;
            IsReadyToShowNextFrame = true;
        }

        public void SetInitialFrame() {
            IsReadyToShowNextFrame = true;
	        HasFinishedShowingLastFrame = false;
            NextFrameIndex = 0;
            ElapsedSecondsThisFrame = 0;
        }

        public bool IsAboutToShowFirstFrame() {
            return IsReadyToShowNextFrame && NextFrameIndex == 0;
        }

	    public bool IsDoneShowingLastFrame() {
		    return HasFinishedShowingLastFrame;
	    }

        public override void Update(GameTime gameTime, bool parallax) {
            // If the previous frame has completed, load the next one.
            if (IsReadyToShowNextFrame) {
                CurrentFrame = Frames[NextFrameIndex];
                Appearance.Texture = CurrentFrame.Texture;
                Body.Width = CurrentFrame.Bounds.Width;
                Body.Height = CurrentFrame.Bounds.Height;
                Body.Position = new Vector2(Body.Position.X, ZoneManager.CurrentZone.Floor-Body.Height);
                IsReadyToShowNextFrame = false;
	            HasFinishedShowingLastFrame = false;
            }
            // Determine if this frame has completed.
            ElapsedSecondsThisFrame += gameTime.ElapsedGameTime.TotalSeconds;
            if (ElapsedSecondsThisFrame > CurrentFrame.Duration) {
                NextFrameIndex = Frames.IndexOf(CurrentFrame)+1;
                if (NextFrameIndex == FrameCount) {
                    NextFrameIndex = 0;
	                HasFinishedShowingLastFrame = true;
                }
                IsReadyToShowNextFrame = true;
                ElapsedSecondsThisFrame -= CurrentFrame.Duration;
            }

        }

    }

}